<?php
/**
* @file $Id: StudentGBGrades.php 534 2007-05-22 04:58:18Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

// to eliminate the errors when switching students
unset($_SESSION['_REQUEST_vars']['modname']);
unset($_SESSION['_REQUEST_vars']['course_period_id']);

$user_student_id  = UserStudentID();
$user_profile     = User('PROFILE');
$user_mp          = UserMP();
$user_mp_list     = GetAllMP('QTR',$user_mp);
$db_date          = DBDate();
$course_period_id = $_REQUEST['course_period_id'];
$user_syear       = UserSyear();
$user_school      = UserSchool();

// since printing needs thos vars that were just unset
$_SESSION['_REQUEST_vars']['bottom_print_modname'] = $_REQUEST['modname'];
$_SESSION['_REQUEST_vars']['bottom_print_cpid']    = $_REQUEST['course_period_id'];

// if this is being included by another program ... don't display the program title
if ($_REQUEST['modname'] != 'Grades/Grades.php') {
	DrawHeader(ProgramTitle());
	$_FOCUS['allow_edit'] = false;
}

if ($user_profile == 'admin') {
	Search('student_id');
	if ($user_student_id) {
		echo "
<form action='" . PreparePHP_SELF(array(),array('course_period_id')) . "' method='POST'>";

		$select = "
	<select name='course_period_id' onchange='this.form.submit();'>
		<option value=''>" . _('Please Select a Course') . "'</option>";
		
		$classes = DBGet(DBQuery("
SELECT       cp.TITLE
 ,           cp.COURSE_PERIOD_ID
 ,           cp.TEACHER_ID
 ,           s.COURSE_ID
 ,           s.COURSE_PERIOD_ID
 ,           c.TITLE AS COURSE_TITLE 
FROM         SCHEDULE s
 ,           COURSE_PERIODS cp
 ,           COURSES c 
WHERE        c.COURSE_ID = cp.COURSE_ID 
 AND         cp.COURSE_PERIOD_ID = s.COURSE_PERIOD_ID 
 AND         s.STUDENT_ID = '$user_student_id' 
 AND         cp.MARKING_PERIOD_ID IN ($user_mp_list) 
 AND      (  '$db_date' BETWEEN s.START_DATE AND s.END_DATE 
  OR         s.END_DATE IS NULL)
		"));  // the enddate null thing doesnt check start_date at all like it does in other places.
		
		foreach ($classes as $class) {
			$select .= "
		<option value='$class[COURSE_PERIOD_ID]'" 
			. ( ($class['COURSE_PERIOD_ID'] == $course_period_id) 
				? ' selected' 
				: '')
		. ">
			$class[COURSE_TITLE] - $class[TITLE]
		</option>";
		}
		
		$select .= "
	</select>";
	
		DrawHeader($select);
		echo "
</form>";
	}
}

if ($course_period_id) {
	$course_RET = DBGet(DBQuery("
SELECT       c.COURSE_ID
 ,           c.TITLE
 ,           cp.TEACHER_ID
 ,           cp.GRADE_SCALE_ID 
FROM         COURSES c
 ,           COURSE_PERIODS cp 
WHERE        cp.COURSE_ID = c.COURSE_ID 
 AND         cp.COURSE_PERIOD_ID = '$course_period_id'
	"));
	
	$course_id      = $course_RET[1]['COURSE_ID'];
	$course         = $course_RET[1]['TITLE'];
	$staff_id       = $course_RET[1]['TEACHER_ID'];
	$grade_scale_id = $course_RET[1]['GRADE_SCALE_ID'];
	
	if (!$_makeGrade[$staff_id]) {
		$username = DBGetValue("
SELECT       USERNAME 
FROM         USERS 
WHERE        STAFF_ID = '$staff_id'
		");
// so why didnt he use a subquery?
		$config_RET = DBGet(DBQuery("
SELECT       TITLE
 ,           VALUE 
FROM         PROGRAM_USER_CONFIG 
WHERE        USERNAME = '$username' 
 AND         PROGRAM = 'Gradebook'
		"), array(), array('TITLE'));
		
		if (count($config_RET)) {
			foreach ($config_RET as $title => $value) {
				$_makeGrade[$staff_id][$title] = $value[1]['VALUE'];
			}
		}
	}
	
	// ASSIGNMENT TYPES	
	$types_RET = DBGet(DBQuery("
SELECT       ASSIGNMENT_TYPE_ID
 ,           TITLE
 ,           FINAL_GRADE_PERCENT 
FROM         GRADEBOOK_ASSIGNMENT_TYPES 
WHERE        STAFF_ID = '$staff_id' 
 AND         COURSE_ID = '$course_id' 
ORDER BY     TITLE	
	"));
	
	// TEACHER PREFS
	if (!$_FOCUS['_makeGrade']['grades']) {
		$_FOCUS['_makeGrade']['grades'] = DBGet(DBQuery("
SELECT       TITLE
 ,           ID
 ,           DEFAULT_BREAKOFF 
FROM         REPORT_CARD_GRADES 
WHERE        SCALE_ID = '$grade_scale_id' 
 AND         SYEAR = '$user_syear' 
 AND         SCHOOL_ID = '$user_school' 
ORDER BY     SORT_ORDER
		"));
	}
	
	$custom = false;
	foreach ($_FOCUS['_makeGrade']['grades'] as $grade) {
		if ($_makeGrade[$staff_id][$course_period_id . '-' . $grade['ID']]) {
			$custom = true;
			break;
		}
	}
	
	if (!$custom) {
		foreach ($_FOCUS['_makeGrade']['grades'] as $grade) {
			$_makeGrade[$staff_id][$course_period_id . '-' . $grade['ID']] // = 
					= $grade['DEFAULT_BREAKOFF'];
		}
	}
	
	
	$functions = array( 'STU_POINTS'    => '_makePoints'
					,   'GRADE'         => '_makeGrade'
					,   'ASSIGNED_DATE' => 'ProperDate'
					,   'DUE_DATE'      => 'ProperDate'
					);
					
	if ($_REQUEST['modname'] == 'Grades/Grades.php') {
		$functions['STU_POINTS'] = '_makeGBGradesPoints';
	}
	
	$assignments_RET = DBGet(DBQuery("
SELECT       gt.ASSIGNMENT_TYPE_ID
 ,           gt.FINAL_GRADE_PERCENT
 ,           ga.ASSIGNMENT_ID
 ,           ga.TITLE
 ,           ga.POINTS
 ,           ga.DUE_DATE
 ,           ga.ASSIGNED_DATE
 ,           gg.POINTS as STU_POINTS
 ,           NULL AS GRADE 
FROM         GRADEBOOK_ASSIGNMENT_TYPES gt
 JOIN        GRADEBOOK_ASSIGNMENTS ga 
  ON         gt.ASSIGNMENT_TYPE_ID = ga.ASSIGNMENT_TYPE_ID 
 LEFT JOIN   GRADEBOOK_GRADES gg 
  ON         gg.ASSIGNMENT_ID = ga.ASSIGNMENT_ID 
   AND       gg.COURSE_PERIOD_ID = '$course_period_id'
WHERE        gg.STUDENT_ID = '$user_student_id'
 AND         ga.STAFF_ID = '$staff_id' 
 AND       ( ga.COURSE_ID = '$course_id' 
  OR         ga.COURSE_PERIOD_ID = '$course_period_id' ) 
 AND         ga.MARKING_PERIOD_ID = '$user_mp' 
ORDER BY     ga.DUE_DATE DESC
	"), $functions);
	
	$LO_columns = array( 'TITLE'         => _('Assignment')
					,    'STU_POINTS'    => _('Points')
					,    'GRADE'         => _('Grade')
					,    'ASSIGNED_DATE' => _('Assigned')
					,    'DUE_DATE'      => _('Due')
					);
	
	$sum_points = 0;
	foreach ($student_points as $assignment_type_id => $points) {
		$sum_points += $points / $total_points[$assignment_type_id];
	}
	
	if (count($types_RET) > 1 
	&&  $_makeGrade[$staff_id]['WEIGHT'] == 'Y'
	){
		$content = "
<table border='0' cellpadding='4' cellspacing='0'>
	<tr>
		<th>&nbsp;</th>";
		
		foreach ($types_RET as $type)
		{
			$content .= "
		<td><b>$type[TITLE]</b></td>";
		}
		
		$content .= "
		<td rowspan='3'>&nbsp;</td>
		<td><b>" . _('Total Points') . "</b></td>";
		
		if ($_makeGrade[$staff_id]['WEIGHT'] == 'Y') {
			$content .= "
		<td bgcolor='#F0F0F1'><b>" . _('Weighted Grade') . "</b></td>";		
		}	
		
		$content .= "
	</tr>
	<tr>
		<th><b>" . _('Percent of Grade') . "</b></th>";
		
		foreach ($types_RET as $type) {
			$content .= "
		<td>" . round($type['FINAL_GRADE_PERCENT'] * 100, 0) . "%</td>";
		}
		
		$content .= "
		<td>100%</td>";
		
		if ($_makeGrade[$staff_id]['WEIGHT'] == 'Y') {
			$content .= "
		<td bgcolor='#F0F0F1'>&nbsp;</td>";
		}
		
		$content .= "
	</tr>
	<tr>";
	
		switch ($user_profile) {
			case 'student': {
				$content .= "
		<th><b>" . _('Your Score') . "</b></th>";
			}   break;
			
			case 'parent': {
				$content .= "
		<th><b>" . _('Your Child\'s Score') . "</b></th>";
			}   break;
			
			default: {
				$content .= "
		<th><b>" . _('Student\'s Score') . "</b></th>";
			}   break;
		}
		
		foreach ($types_RET as $type) {
			$percent = $student_points[$type['ASSIGNMENT_TYPE_ID']] 
							/ $type['FINAL_GRADE_PERCENT'] 
							/ $total_points[$type['ASSIGNMENT_TYPE_ID']];
							
			$THIS_RET['STU_POINTS'] = $percent * 100;
			$THIS_RET['POINTS'] = 100;
			$content .= "
		<td>" . ($student_points[$type['ASSIGNMENT_TYPE_ID']] / $type['FINAL_GRADE_PERCENT']) 
			  . " / "
			  . $total_points[$type['ASSIGNMENT_TYPE_ID']]
			  . " &nbsp;"
			  . _makeGrade($percent, "") . "
		</td>";
		}
		
		$content .= "
		<td bgcolor='#F0F0F1'>$nonweighted_student_points / $nonweighted_total_points";
		
		if ($_makeGrade[$staff_id]['WEIGHT'] != 'Y') {
			$percent = $nonweighted_student_points / $nonweighted_total_points;
			$THIS_RET['STU_POINTS'] = $percent * 100;
			$THIS_RET['POINTS'] = 100;
			$content .= " &nbsp;<b>" . _makeGrade($percent, "&nbsp;") . "</b>";
		}
		else
		{
			$THIS_RET['STU_POINTS'] = $sum_points * 100;
			$THIS_RET['POINTS'] = 100;
			$content .= "
		</td>
		<td bgcolor='#F0F0F1'><b>" . _makeGrade($sum_points, "&nbsp;") . "</b>";
		}
		$content .= "
		</td>
	</tr>
</table>";

		DrawHeader($content);
		echo '<br />';
	}
	elseif (count($assignments_RET) != 0)	{	
		$THIS_RET = array('STU_POINTS' => ($sum_points * 100)
						, 'POINTS'     => '100'
						);
						
		DrawHeader( button('dot','00FF00','','10')
				.   ' ' 
				.   _(' Current grade in class: ') 
				.   _makeGrade($sum_points, '')
				);
	}
	
	ListOutput( $assignments_RET
			,   $LO_columns
			,   _('Assignment')
			,   _('Assignments')
			,   $link
			,   array()
			,   array('center'   => false
					, 'download' => false
					, 'search'   => false
					)
			);
}
else {
//it would be nice if we gave them some instructions to pick a class...
}

// THIS FUNCTION IS IDENTICAL TO _makePoints(), except that it allows the grade to be edited by a teacher 
//(when this program is included by Gradebook Grades.php)
function _makeGBGradesPoints($value,$column)
{	global $THIS_RET
	,      $total_points
	,      $student_points
	,      $current_RET
	,      $_makeGrade
	,      $staff_id
	,      $nonweighted_student_points
	,      $nonweighted_total_points
	;
	
	$assignment_id = $THIS_RET['ASSIGNMENT_ID'];
	$field_name = "values[$_REQUEST[student_id]][$assignment_id][POINTS]";
	if ($value == '-1') {
		return "
<!-- Table Generated by _makeGBGradesPoints( value=$value, column=$column ) -->
			<table border='0' cellspacing='0' cellpadding='0' class='innerLO_field'>
				<tr>
					<td> 
					" . TextInput( "*"
								,  $field_name
								,  ""
								,  " size='2' maxlength='7'"
								,  "force"
								) . "
					</td>
					<td> &nbsp;/&nbsp; </td>
					<td>$THIS_RET[POINTS]</td>
				</tr>
			</table>";
	}
	else {
		if ($_makeGrade[$staff_id]['WEIGHT'] != 'Y') {
			$THIS_RET['FINAL_GRADE_PERCENT'] = $THIS_RET['ASSIGNMENT_TYPE_ID'] = 1;
		}
						
		$total_points[$THIS_RET['ASSIGNMENT_TYPE_ID']] += $THIS_RET['POINTS'];
		$nonweighted_student_points += $value;
		$nonweighted_total_points += $THIS_RET['POINTS'];
		$student_points[$THIS_RET['ASSIGNMENT_TYPE_ID']] // += 
				+= $value * $THIS_RET['FINAL_GRADE_PERCENT'];

		return "
<!-- Table Generated by _makeGBGradesPoints( value=$value, column=$column ) -->
			<table border='0' cellspacing='0' cellpadding='0' class='innerLO_field'>
				<tr>
					<td>
					" . TextInput( ($value * 1)
								,  $field_name
								,  ""
								,  " size='2' maxlength='7'"
								,  "force"
								) . "
					</td>
					<td> &nbsp;/&nbsp; </td>
					<td>$THIS_RET[POINTS]</td>
				</tr>
			</table>";
	}
}

function _makePoints($value,$column)
{	global $THIS_RET
	,      $total_points
	,      $student_points
	,      $current_RET
	,      $_makeGrade
	,      $staff_id
	,      $nonweighted_student_points
	,      $nonweighted_total_points
	;
	
	if ($value == '-1') {
		return _('N/A') . ' / ' . $THIS_RET['POINTS'];
	}
	else {
		if ($_makeGrade[$staff_id]['WEIGHT'] != 'Y') {
			$THIS_RET['FINAL_GRADE_PERCENT'] = $THIS_RET['ASSIGNMENT_TYPE_ID'] = 1;
		}
						
		$total_points[$THIS_RET['ASSIGNMENT_TYPE_ID']] += $THIS_RET['POINTS'];
		$nonweighted_student_points += $value;
		$nonweighted_total_points += $THIS_RET['POINTS'];
		$student_points[$THIS_RET['ASSIGNMENT_TYPE_ID']] //  +=
				+= $value * $THIS_RET['FINAL_GRADE_PERCENT'];

		return ($value * 1) . ' / ' . $THIS_RET['POINTS'];
	}
}

function _makeGrade($value,$column)
{	global $_makeGrade
	,      $THIS_RET
	,      $staff_id
	,      $course_period_id
	,      $_FOCUS
	,      $grade_scale_id
	;
	
	if ($THIS_RET['STU_POINTS'] 
	&& $THIS_RET['STU_POINTS'] != '-1'
	){
		$percent = $THIS_RET['STU_POINTS'] / $THIS_RET['POINTS'];
	}
	elseif ($THIS_RET['STU_POINTS'] == '-1') {
		return _('N/A');
	}
	elseif ($THIS_RET['POINTS'] == 0) {
		return _('EC');
	}
	else {
		$percent = '0';
	}

	if ($_makeGrade[$staff_id]['ROUNDING'] == 'UP') {
		$percent = ceil($percent * 100);
	}
	elseif ($_makeGrade[$staff_id]['ROUNDING'] == 'DOWN') {
		$percent = floor($percent * 100);
	}
	else {
		$percent = round($percent * 100, 0);
	}

	//$grades = array('A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','F');

	foreach ($_FOCUS['_makeGrade']['grades'] as $grade) {
		if ($percent >= $_makeGrade[$staff_id][$course_period_id . '-' . $grade['ID']] 
		&&  is_numeric($_makeGrade[$staff_id][$course_period_id . '-' . $grade['ID']])
		){
			return "$percent% $grade[TITLE]";
		}
	}
	
	// we'll only reach here if the student's percent doesn't apply to any grade
	return "$percent%";
}
?>